from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
from wechat_mini import models
from utils import mypage
from django.db.models import Q
from django.core import serializers
import json
from django.contrib import auth
# Create your views here.

user={
    "globaluser":''
}
#首页
def test(request):
    user_obj = models.TeacherInfo.objects.filter(pk=user["globaluser"]).first()
    keshi_queryset = models.ClassInfo.objects.all()
    list1 = []
    if request.method=='POST':
        classname=request.POST.get('class_select')
        kaoqin_obj = models.KaoQin.objects.filter(classid=classname).all()
        res = models.ClassInfo.objects.filter(classroomnum=classname).values('rowcolumn', 'rowline').first()
        qinjia_obj=models.StudentLeave.objects.filter(classnum=classname).all()
        keshi_obj = models.ClassInfo.objects.filter(classroomnum=classname).first()
        print(classname)
        row = int(res['rowline'])
        col = int(res['rowcolumn'])
        yidaonum=kaoqin_obj.count()
        qingjianum=qinjia_obj.count()
        weidaonum=(int(row)*int(col))-(yidaonum+qingjianum)
        # list1=[]
        for i in range(1, row+1):
            for j in range(1, col+1):
                list1.append('{}-{}'.format(i, j))
    return render(request,'test.html',locals())

def home(request):
    book_list = models.StudentLeave.objects.all()
    current_page = request.GET.get("page", 1)
    all_count = book_list.count()
    askleave_obj = mypage.Pagination(current_page=current_page, all_count=all_count, per_page_num=2)
    askleave_queryset = book_list[askleave_obj.start:askleave_obj.end]
    return render(request,'home.html', locals())
#登录
def tlogin(request):
    if request.method=="POST":
        back_dic={"code":'',"msg":''}
        teanum=request.POST.get("username")
        password=request.POST.get("password")
        tea_obj=models.TeacherInfo.objects.filter(teanum=teanum).first()
        if not tea_obj:
            back_dic["code"] = 202
            back_dic["msg"] = '用户不存在！！！'
            return JsonResponse(back_dic)
        if tea_obj.pk==teanum and tea_obj.password==password:
            back_dic["code"]=200
            back_dic["url"]='/index/'
            back_dic["msg"]='登录成功'
            user["globaluser"]=teanum
            return JsonResponse(back_dic)
        back_dic["code"] = 201
        back_dic["msg"] = '账号或密码错误！！！'
        return JsonResponse(back_dic)
    return render(request,'tlogin.html')
#首页
def index(request):
    user_obj=models.TeacherInfo.objects.filter(pk=user["globaluser"]).first()
    return render(request,'index.html',locals())
#修改密码
def edit_pwd(request):
    if request.method=="POST":
        back_dic={"code":'',"msg":''}
        json_str=json.loads(request.body)
        teaname=json_str['username']
        old_password=json_str['old_password']
        new_password=json_str['new_password']
        confirm_password=json_str['confirm_password']
        print(teaname,old_password, new_password, confirm_password)
        if new_password==confirm_password:
            user_obj=models.TeacherInfo.objects.filter(teaname=teaname).first()
            if user_obj.password==old_password:
                models.TeacherInfo.objects.filter(teaname=teaname).update(password=new_password)
                back_dic["code"]=200
                back_dic["url"]='tea_admin/tlogin/'
                back_dic["msg"]='更新成功！！！'
                return JsonResponse(back_dic)
        back_dic["code"] = 201
        back_dic["url"] = 'tea_admin/tlogin/'
        back_dic["msg"] = '两次密码不一致,请重新输入！！！'
        return JsonResponse(back_dic)
#退出登录
def logout(request):
    user['globaluser']=''
    return redirect('tea_admin:tlogin')
#考勤管理
def kaoqin_gl(request):
    user_obj = models.TeacherInfo.objects.filter(pk=user["globaluser"]).first()
    kaoqin_list = models.KaoQin.objects.all()
    current_page = request.GET.get("page", 1)
    all_count = kaoqin_list.count()
    kaoqin_obj = mypage.Pagination(current_page=current_page, all_count=all_count, per_page_num=10)
    kaoqin_queryset = kaoqin_list[kaoqin_obj.start:kaoqin_obj.end]
    return render(request,'kaoqin_gl.html', locals())
#考勤管理编辑
def kaoqin_edit(request,edit_id):
    kaoqin_obj = models.KaoQin.objects.filter(attendid=edit_id).first()
    kaoqin_queryset=models.KaoQin.objects.all()
    if request.method=="POST":
        print(request.POST)
        statue=request.POST.get('statue')
        models.KaoQin.objects.filter(attendid=edit_id).update(attendanceresult=statue)
        return redirect('/tea_admin/kaoqin_gl/')
    return render(request,'kaoqin_edit.html',locals())
#考勤管理删除
def kaoqin_del(request):
    if request.method=="POST":
        back_dic = {"code": '', "msg": ''}
        delete_id=request.POST.get('delete_id')
        models.KaoQin.objects.filter(attendid=delete_id).delete()
        back_dic["code"]=200
        back_dic["msg"]='删除成功!!!'
        return JsonResponse(back_dic)
#请假管理
def askleave(request):
    user_obj=models.TeacherInfo.objects.filter(pk=user["globaluser"]).first()
    askleave_list = models.StudentLeave.objects.all()
    current_page = request.GET.get("page", 1)
    all_count = askleave_list.count()
    askleave_obj = mypage.Pagination(current_page=current_page, all_count=all_count, per_page_num=5)
    askleave_queryset = askleave_list[askleave_obj.start:askleave_obj.end]
    return render(request,'askleave.html', locals())
#请假管理编辑
def askleave_edit(request,edit_id):
    askleave_obj = models.StudentLeave.objects.filter(pk=edit_id).first()
    askleave_queryset=models.StudentLeave.objects.all()
    if request.method=="POST":
        print(request.POST)
        statue=request.POST.get('statue')
        teareason=request.POST.get('teareason')
        models.StudentLeave.objects.filter(pk=edit_id).update(status=statue,teareason=teareason)
        res=models.StudentLeave.objects.filter(pk=edit_id).first()
        return redirect('/tea_admin/askleave/')
    return render(request,'askleave_edit.html',locals())
#请假管理删除
def askleave_del(request):
    if request.method == "POST":
        back_dic = {"code": '', "msg": ''}
        delete_id = request.POST.get('delete_id')
        models.StudentLeave.objects.filter(pk=delete_id).delete()
        back_dic["code"] = 200
        back_dic["msg"] = '删除成功!!!'
        return JsonResponse(back_dic)
#课程表展示
def showcourse(request):
    user_obj = models.TeacherInfo.objects.filter(pk=user["globaluser"]).first()
    return render(request,'showcourse.html',locals())
#课室创建
def classcreate(request):
    user_obj = models.TeacherInfo.objects.filter(pk=user["globaluser"]).first()
    keshi_queryset = models.ClassInfo.objects.all()
    if request.method=='POST':
        back_dic={"code":'',"msg":''}
        # print(request.POST)
        row=request.POST.get('row')
        col=request.POST.get('col')
        coursename=request.POST.get('coursename')
        classname=request.POST.get('classname')
        stunum=request.POST.get('stunum')
        # keshi_queryset = models.ClassInfo.objects.all()
        seatnum=str(int(row)*int(col))
        models.ClassInfo.objects.create(rowline=row,rowcolumn=col,coursename=coursename,classroomnum=classname,studentnum=stunum,seatnum=seatnum)
        back_dic["code"]=200
        back_dic["msg"]='创建成功'
        back_dic["url"]='/tea_admin/classcreate/'
        return JsonResponse(back_dic)
        # return redirect('/tea_admin/classcreate/')
    return render(request,'classcreate.html',locals())
#课室管理
def classmanage(request):
    user_obj = models.TeacherInfo.objects.filter(pk=user["globaluser"]).first()
    keshi_queryset = models.ClassInfo.objects.all()
    list1 = []
    if request.method=='POST':
        coursename=request.POST.get('course_select')
        classname=request.POST.get('class_select')
        kaoqin_obj = models.KaoQin.objects.filter(classid=classname).all()
        res = models.ClassInfo.objects.filter(Q(classroomnum=classname),Q(coursename=coursename)).values('rowcolumn', 'rowline').first()
        qinjia_obj=models.StudentLeave.objects.filter(Q(classnum=classname),Q(course=coursename)).all()
        keshi_obj = models.ClassInfo.objects.filter(Q(classroomnum=classname),Q(coursename=coursename)).first()
        print(classname)
        row = int(res['rowline'])
        col = int(res['rowcolumn'])
        yidaonum=kaoqin_obj.count()
        qingjianum=qinjia_obj.count()
        weidaonum=int(keshi_obj.studentnum)-(yidaonum+qingjianum)
        # list1=[]
        for i in range(1, row+1):
            for j in range(1, col+1):
                list1.append('{}-{}'.format(i, j))
    return render(request,'classmanage.html',locals())
#查看课室创建
def checkclass(request):
    keshi_queryset = models.ClassInfo.objects.all()
    if request.method=='GET':
        back_dic={"list":[]}
        class_select=request.GET.get('class_select')
        # print(class_select)
        res = models.ClassInfo.objects.filter(classroomnum=class_select).values('rowcolumn', 'rowline').first()
        row = int(res['rowline'])
        col = int(res['rowcolumn'])
        list1 = []
        for i in range(1, row+1):
            for j in range(1, col+1):
                list1.append('{}-{}'.format(i, j))
        back_dic["list"]=list1
        back_dic["row"]=row
        back_dic["col"]=col
        return JsonResponse(back_dic)
    return render(request, 'classcreate.html', locals())
#考勤搜索查询
def kaoqinsearch(request):
    if request.method == 'POST':
        scontent=request.POST.get('scontent')
        q=Q()
        q.connector='or'
        q.children.append(('stuname',scontent))
        q.children.append(('stunum',scontent))
        q.children.append(('classid',scontent))
        # print(scontent)
        res=models.KaoQin.objects.filter(q)
        req=serializers.serialize('json',res)
        return HttpResponse(req)
#请假搜索查询
def askleavesearch(request):
    if request.method == 'POST':
        scontent=request.POST.get('scontent')
        print(scontent)
        q=Q()
        q.connector='or'
        q.children.append(('stuname',scontent))
        q.children.append(('stunum',scontent))
        q.children.append(('status',scontent))
        # print(scontent)
        res=models.StudentLeave.objects.filter(q)
        req=serializers.serialize('json',res)
        return HttpResponse(req)